package com.hw.one.collect.util;

import com.alibaba.fastjson.JSONObject;
import com.hw.one.collect.config.ConditionConfig;
import com.hw.one.collect.po.OneToken;
import com.hw.one.collect.po.SiteAirConcentrationPO;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Administrator on 2017/8/30.
 *
 * one平台认证 类
 */
public class OneAuthUtil {


    private static String reqType = "http://";

    private static String ip_address = ConditionConfig.get("oneIp", "auth");
    private static String port = ConditionConfig.get("onePort", "auth");

    public String httpPre = reqType + ip_address + ":" + port;
    private final static String GET_TOKEN_URL = "/api/authen/authen?format=json";
    private final static String REFRESH_TOKEN_URL = "/api/authen/token/refresh?format=json";

    private static final long SECOND_2_MILLIS = 1000L;

    private static OneAuthUtil instance;
    private OneToken token;

    private long lastTokenTime = 0L;

    public String tokenValue = null;
    public String refreshToken = null;

    private long timeout = 3600 * SECOND_2_MILLIS;
    private static Properties properties = new Properties();

    private static String accountName = ConditionConfig.get("oneUser", "auth");
    private  static String password = ConditionConfig.get("onePassword", "auth");


    /**
     * 获取实例
     *
     * @return
     */
    public static synchronized OneAuthUtil getInstance(){
        if(instance == null){
            instance = new OneAuthUtil();
        }
        return instance;
    }


    /**
     * 验证token是否合法
     *
     * @return
     */
    private boolean isValidToken() {
        if (token == null){
            return false;
        }
        long currTime = System.currentTimeMillis();
        return lastTokenTime > currTime;
    }


    /**
     * 获取token
     *
     * @return
     */
    public String getAccessToken(){
        if (isValidToken()){
            tokenValue = token.getToken();
            return tokenValue;
        }
        if (getNewToken()){
            tokenValue = token.getToken();
            return tokenValue;
        }
        return null;
    }

    /**
     *
     * 获取验证请求头
     *
     * @return
     */
    public Map<String, String> getAuthHeader() {
        Map<String,String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + getAccessToken());
        return header;
    }

    /**
     * 重新获取一个新的token
     *
     * @return true 获取成功, false 获取失败
     */
    private boolean getNewToken(){
        try{
            if (null != refreshToken) {
                token = executeRefreshTokenHttpRequest();
            }else {
                token = executeHttpRequest();
            }
        } catch (Exception e) {
            token = null;
            lastTokenTime = 0;
            return false;
        }
        refreshToken = token.getRefreshToken();
        lastTokenTime = System.currentTimeMillis() + token.getExpire();
        return true;
    }


    /**
     * 发送请求，刷新token
     * @return
     */
    private OneToken executeRefreshTokenHttpRequest() {

        Map<String, String> body = new HashMap<>();
        body.put("refreshToken", refreshToken);
        String url = reqType + ip_address + ":" + port + REFRESH_TOKEN_URL;
        Map<String, String> result = HttpClientUtil.sendPost(url, new HashMap<String, String>(), body);
        if (null != result && "200".equals(result.get("statusCode"))) {
            JSONObject obj = JSONObject.parseObject(result.get("result"));
            return JSONObject.parseObject(obj.getString("data"), OneToken.class);
        }

        return null;
    }

    /**
     * 发送请求 获取token
     *
     * @return
     */
    private OneToken executeHttpRequest() {
        Map<String, String> body = new HashMap<>();
        body.put("accountName", accountName);
        body.put("password", password);
        String url = reqType + ip_address + ":" + port + GET_TOKEN_URL;

        Map<String, String> result = HttpClientUtil.sendPost(url, new HashMap<String, String>(), body);
        if (null != result && "200".equals(result.get("statusCode"))) {
            JSONObject obj = JSONObject.parseObject(result.get("result"));
            return JSONObject.parseObject(obj.getString("data"), OneToken.class);
        }
        return null;
    }


    public static void main(String[] args) {
        try {
            DecimalFormat df = new DecimalFormat("######.##");
            OneAuthUtil oneAuth = OneAuthUtil.getInstance();
            // 获取验证请求头
            Map<String, String> header = oneAuth.getAuthHeader();
            String url = oneAuth.httpPre + "/api/alarmDetermine/determineAndSendAlarmInformation?format=json";

            Map<String, String> body = new HashMap<>();
            body.put("code", "nationalThreshold");
            String[] ruleParamSet = new String[9];

            ruleParamSet[0] = "温度|23";
            ruleParamSet[1] = "湿度|56";
            ruleParamSet[2] = "PM10|10";
            ruleParamSet[3] = "PM10|10%";
            ruleParamSet[4] = "PM25|25";
            ruleParamSet[5] = "SO2|12";
            ruleParamSet[6] = "NO2|32";
            ruleParamSet[7] = "CO|0.88";
            ruleParamSet[8] = "O3|110";

            String ruleParams = StringUtil.join(ruleParamSet, ",");
            System.out.println("---------------ruleParams:" + ruleParams);
            body.put("ruleParams", ruleParams);
            body.put("siteCode", "410100062");
            body.put("siteName", "银行学校");
            Map<String, String> response = HttpClientUtil.sendPost(url, header, body);
            dealResponse(response);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void  dealResponse(Map<String,String> response) {
        if (null != response && "200".equals(response.get("statusCode"))) {
            System.out.println("--------------------------------------");
            System.out.println(response.get("result"));
            System.out.println("---------------------------------------");
        }else {
            System.out.println("-------------------请求失败------------");
        }
    }


}
